package cn.com.anypay.manager.service.impl;

import cn.com.anypay.manager.service.LoginAuthService;
import cn.com.anysdk.core.util.ValidationUtils;
import cn.com.anysdk.sms.api.ISmsService;
import cn.com.anysdk.sms.api.SmsRequest;
import cn.com.anysdk.sms.api.SmsResponse;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class LoginAuthServiceImpl implements LoginAuthService {

    @Resource
    private ISmsService smsService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private static final String SMS_CODE_PREFIX = "sms:code:";
    private static final long SMS_CODE_EXPIRE_MINUTES = 5;

    @Value("${anysdk.sms.aliyun.signName}")
    private String signName;

    @Value("${anysdk.sms.aliyun.defaultTemplateId}")
    private String templateId;

    @Override
    public boolean senSmsCode(Map<String, String> request) {
        String phoneNumber = request.get("phoneNumber");
        if (ValidationUtils.isEmpty(phoneNumber)) {
            throw new IllegalArgumentException("手机号不能为空");
        } else if (!ValidationUtils.isPhone(phoneNumber)) {
            throw new IllegalArgumentException("手机号格式不正确");
        }

        try {
            // 生成6位随机验证码
            String code = generateVerificationCode();
            String redisKey = SMS_CODE_PREFIX + phoneNumber;

            // 存储验证码到Redis，设置5分钟过期
            stringRedisTemplate.opsForValue().set(redisKey, code, SMS_CODE_EXPIRE_MINUTES, TimeUnit.MINUTES);

            // 构建短信请求
            SmsRequest smsRequest = SmsRequest.builder()
                    .phoneNumber(phoneNumber)
                    .signName(signName)
                    .templateId(templateId)
                    .templateParams(Map.of("code", code))
                    .build();

            log.info("发送短信请求参数: phoneNumber={}", phoneNumber);

            // 发送短信
            SmsResponse response = smsService.send(smsRequest);

            if (response != null && response.isSuccess()) {
                log.info("向手机号 {} 发送验证码成功", phoneNumber);
                return true;
            } else {
                // 发送失败，删除Redis中的验证码
                stringRedisTemplate.delete(redisKey);
                log.error("向手机号 {} 发送验证码失败", phoneNumber);
                return false;
            }
        } catch (Exception e) {
            log.error("发送验证码异常: {}", e.getMessage(), e);
            return false;
        }
    }

    @Override
    public Map<String, Object> verifySmsCode(Map<String, String> request) {
        String phoneNumber = request.get("phoneNumber");
        String code = request.get("code");
        if (ValidationUtils.isEmpty(phoneNumber)) {
            throw new IllegalArgumentException("手机号不能为空");
        }
        if (ValidationUtils.isEmpty(code)) {
            throw new IllegalArgumentException("验证码不能为空");
        }

        String redisKey = SMS_CODE_PREFIX + phoneNumber;
        String cachedCode = stringRedisTemplate.opsForValue().get(redisKey);

        if (cachedCode == null) {
            log.warn("验证码验证失败，手机号:{}，原因: 未找到验证码或已过期", phoneNumber);
            return Map.of(
                "success", false,
                "message", "验证码已过期或不存在"
            );
        }

        if (!code.equals(cachedCode)) {
            log.warn("验证码验证失败，手机号:{}，原因: 验证码不正确", phoneNumber);
            return Map.of(
                "success", false,
                "message", "验证码不正确"
            );
        }

        // 验证通过后删除验证码，防止重复使用
        stringRedisTemplate.delete(redisKey);
        log.info("手机号:{} 验证码验证通过", phoneNumber);
        
        // 返回验证成功和用户信息
        return Map.of(
            "success", true,
            "message", "验证成功",
            "data", Map.of(
                "phoneNumber", phoneNumber,
                "token", generateToken(phoneNumber)
            )
        );
    }

    /**
     * 生成6位数字验证码
     */
    private String generateVerificationCode() {
        Random random = new Random();
        return String.format("%06d", random.nextInt(1000000));
    }

    /**
     * 生成用户token
     * @param phoneNumber 手机号
     * @return token字符串
     */
    private String generateToken(String phoneNumber) {
        // TODO: 实现真实的token生成逻辑，可以使用JWT等
        return UUID.randomUUID().toString();
    }
}
